package mock

import (
	"context"
	"fmt"
	"time"

	"gitee.com/go-course/go12/devcloud-mini/cmdb/apps/secret"
	"github.com/infraboard/mcube/exception"
	"go.mongodb.org/mongo-driver/bson"
)

func (i *impl) CreateSecret(
	ctx context.Context,
	in *secret.CreateSecretRequest,
) (*secret.Secret, error) {
	i.log.Debug().Msgf("save secret ...")

	// 请求的校验
	if err := i.validator.Struct(in); err != nil {
		return nil, exception.NewBadRequest(err.Error())
	}

	// 构建secret对象
	ins := secret.NewSecret(in)

	// 入库
	if _, err := i.col.InsertOne(ctx, ins); err != nil {
		return nil, err
	}

	return ins, nil
}

// 查询secret
func (i *impl) DescribeSecret(
	ctx context.Context,
	in *secret.DescribeSecretRequest) (
	*secret.Secret, error) {
	ins := secret.NewSecret(nil)
	err := i.col.FindOne(ctx, bson.M{"_id": in.Id}).Decode(ins)
	if err != nil {
		return nil, err
	}
	return ins, nil
}

// 使用云商凭证同步资源 Stream
func (i *impl) SyncResource(
	ctx context.Context,
	in *secret.SyncResourceRequest,
	hook secret.SyncResourceHandler) error {

	for i := 1; i < 51; i++ {
		hook(&secret.SyncResponse{
			Id:   fmt.Sprintf("cvm%d", i),
			Name: fmt.Sprintf("cvm%d", i),
		})
		time.Sleep(1 * time.Second)
	}

	return nil
}
